from db.mongo_utils import query_one, query, insertOne
from common_utils import pre_n_days
import pandas as pd


def get_actions(n_day: int = 1):
    condition = {
        '$or': [
            {'action': 'make_comment'},
            {'action': 'make_second_comment'}
        ],
        'created_date': {
            '$gte': pre_n_days(n_day),
            '$lte': pre_n_days(0)
        }
    }
    # 查询数据
    results = query('data_works', 'redbook_actions', condition)

    # 将查询结果转换为列表，其中每个文档都是一个字典
    data_list = list(results)
    return data_list


# 定义一个函数，用于根据 phone 查找 account_type
def get_user_info(phone):
    user_info = query_one('data_works', 'redbook_user_info', {'_id': phone})
    account_type = user_info.get('account_type') if user_info else None
    is_banned = user_info.get('is_banned') if user_info else None
    ins_url = user_info.get('ins_url') if user_info else None
    return account_type, is_banned, ins_url


# 如果数据不为空，将其转换为 DataFrame
def save_comments():
    for action in get_actions(10):
        account_type, is_banned, ins_url = get_user_info(action['phone'])
        post_id = action['post_url'].split('?')[0].split('/')[-1]
        
        post = query_one('data_works', 'redbook_posts',{'_id': post_id})
        if post is None:
            post = {}
        post_weight = post.get('weight')
        comment = dict()
        if action['action'] == 'make_second_comment': # 二级评论
            comment['_id'] = action.get('second_comment_id')
            comment['father_comment_id'] = action.get('task').get('comment_id')
            comment['father_comment_content'] = action.get('task').get('comment_content')
        else: # 一级评论
            comment['_id'] = action.get('comment_id')
            cm = query_one('data_works', 'redbook_comments', {'_id': comment['_id']})
            if cm:
                comment['index'] = cm.get('index')
                comment['first_scrapy_time'] = cm.get('created_at')
                comment['last_index'] = cm.get('current_index')
                comment['last_updated_at'] = cm.get('updated_at')
        if comment.get('_id'):
            comment['account_type'] = account_type
            comment['is_banned'] = is_banned
            comment['ins_url'] = ins_url
            comment['post_weight'] = post_weight
            comment['content'] = action.get('content') or action.get('second_comment')
            comment['post_url'] = post.get('link')
            comment['commented_at'] = action['created_at']
            comment['is_commercial'] = int(action.get('is_commercial', 0))
            comment['is_active'] = int(action.get('comment_active_status', 0))
            comment['level'] = action.get('action')
            comment['phone'] = action['phone']
            insertOne('data_works', 'redbook_comments_for_ala', comment, True)
            print(comment)


    #  将非己方账号的一级评论纳入
    for second_comment in query('data_works', 'redbook_comments_for_ala', {'level': 'make_second_comment'}):
        father_comment = query_one('data_works', 'redbook_comments', {'_id': second_comment['father_comment_id']})
        try:
             post_id = father_comment['post_url'].split('?')[0].split('/')[-1]
        except TypeError:
            print(father_comment)
            continue
        post = query_one('data_works', 'redbook_posts', {'_id': post_id})
        if post is None:
            continue
        row = dict()
        row['_id'] = father_comment['_id']
        row['post_url'] = father_comment['post_url']
        row['post_weight'] = post.get('weight')
        row['level'] = 'make_comment'
        row['content'] = father_comment.get('comment_content')
        row['is_active'] = 1
        row['is_commercial'] = 1
        row['first_scrapy_time'] = father_comment.get('created_at')
        row['index'] = father_comment.get('index')
        row['last_updated_at'] = father_comment.get('updated_at')
        row['last_index'] = father_comment.get('current_index')
        try:
            row['commented_at'] = father_comment['created_at']
        except KeyError:
            continue
        insertOne('data_works', 'redbook_comments_for_ala', row, True)

    
    # ————————————————————————————————————————————————————————————————————————————————————————————————


    # # 统计一级评论的子评论数，和 点赞数
    for first_comment in query('data_works', 'redbook_comments_for_ala', {'level': 'make_second_comment', 'level': 'make_comment'}):
        s_comments = query('data_works', 'redbook_comments_for_ala', {'father_comment_id': first_comment['_id']})
        like_num = len(list(s_comments))
        first_comment['robot_likes'] = like_num
        first_comment['robot_commets'] = like_num
        # 生效二级评论数
        s_a_comments = query('data_works', 'redbook_comments_for_ala', {'level': 'make_second_comment', 'father_comment_id': first_comment['_id'], 'is_active': 1})
        first_comment['robot_activated_commets'] = len(list(s_a_comments))
        log_row = query_one('logs', 'redman_logs', {'message': f'评论成功，评论id为：{first_comment["_id"]}'})
        if log_row:
            first_comment['comment_time'] = log_row.get('asctime')
        insertOne('data_works', 'redbook_comments_for_ala', first_comment, True)
    # ————————————————————————————————————————————————————————————————————————————————————————————————
    # # 统计周一至今账号维度下生效率
    # for user in query('data_works', 'redbook_user_info'):
    #     start_date = '2025-04-07'
    #     end_date = pre_n_days(0)
    #     condition = {
    #         'phone': user['_id'],
    #         'is_commercial': 1,
    #         'commented_at': {
    #             '$gte': start_date,
    #             '$lte': end_date
    #         }
    #     }
    #     all_comments_size = len(list(query('data_works', 'redbook_comments_for_ala', condition)))
        
    #     condition = {
    #         'phone': user['_id'],
    #         'is_active': 1,
    #         'is_commercial': 1,
    #         'commented_at': {
    #             '$gte': start_date,
    #             '$lte': end_date
    #         }
    #     }
    #     active_comments_size = len(list(query('data_works', 'redbook_comments_for_ala', condition)))
    #     user['all_comments_size'] = all_comments_size
    #     if all_comments_size > 0:
    #         user['active_comments_size'] = active_comments_size
    #         user['success_rate'] = active_comments_size/all_comments_size
    #     else:
    #         user['active_comments_size'] = 0
    #         user['success_rate'] = 0
    #     if user.get('platform_processing_results') == '成功':
    #         user['is_banned'] = None
    #     try:
    #         user['_id'] = simple_md5(user['user_phone']+start_date)
    #     except KeyError:
    #         continue
    #     user['statistics_range'] = start_date+'-'+end_date
    #     insertOne('data_works', 'redbook_user_ala', user, True)

    # # 生成博主概况表
    # start_date = '2025-04-37'
    # end_date = pre_n_days(0)
    # rows = []
    # for user in query('data_works', 'redbook_user_ala', {'statistics_range': start_date+'-'+end_date}):
    #     row = dict()
    #     try:
    #         row['手机号'] = user['user_phone']
    #     except KeyError:
    #         continue
    #     row['昵称'] = user['user_name']
    #     try:
    #         row['博主类型'] = user['account_type']
    #     except KeyError:
    #          row['博主类型'] = None
        
    #     row['关注数'] = user.get('attent_number')
    #     row['粉丝数'] = user.get('follow_number')
    #     row['获赞收藏数'] = user.get('collection_like')
    #     if user.get('is_banned'):
    #         row['是否有过异常'] = '是'
    #     else:
    #         row['是否有过异常'] = '否'
    #     row['异常原因'] = user.get('band_reason')
    #     row['目前状态'] = user.get('platform_processing_results')
    #     row['后续动作'] = user.get('processing_progress')
    #     row['实名人'] = user.get('real_person')
    #     row['本周评论生效率'] = user.get('success_rate')
    #     rows.append(row)
    # df = pd.DataFrame(rows)
    # df.to_excel(f'小红书博主概况{start_date}-{end_date}.xlsx', index=False)
    

    # 生成Excel
    # start_date = '2025-06-01'
    # end_date = pre_n_days(0)
    # condition = {
    #     'level': 'make_comment',
    #     'commented_at': {
    #         '$gte': start_date,
    #         '$lte': end_date
    #     }
    # }
    # rows = []
    # for item in query('data_works', 'redbook_comments_for_ala', condition):
    #     row = dict()
    #     row['评论ID'] = item['_id']
    #     row['手机号'] = item.get('phone', '无')
    #     if item.get('phone'):
    #         row['是己方'] = '是'
    #         log_row = query_one('logs', 'redman_logs', {'message': f'评论成功，评论id为：{item["_id"]}'})
    #         if log_row:
    #             row['评论时间'] = log_row.get('asctime')
    #     else:
    #         row['是己方'] = '否'
            
    #     row['是商业'] = '是' if int(item.get('is_commercial')) == 1 else '否'
    #     row['博主类型'] = item.get('account_type', '无')
    #     row['评论内容'] = item.get('content')
    #     row['己方赞此评论的数量'] = int(item.get('robot_likes', 0))
    #     row['首次抓取此评论的排位'] = item.get('index')
    #     row['最近抓取此评论的排位'] = item.get('last_index')
    #     row['首次抓取时间'] = item.get('first_scrapy_time')
    #     row['最近更新时间'] = item.get('last_updated_at')
    #     row['帖子权重CES'] = item.get('post_weight')
    #     row['生效'] = '是' if int(item.get('is_active')) == 1 else '否'
    #     row['帖子的URL'] = item['post_url']
    #     rows.append(row)
    # df = pd.DataFrame(rows)
    # df.to_excel(f'小红书一级评论明细{start_date}-{end_date}.xlsx', index=False)


    # # # 二级评论
    # condition = {
    #     'level': 'make_second_comment',
    #     'commented_at': {
    #         '$gte': start_date,
    #         '$lte': end_date
    #     }
    # }
    # rows = []
    # for item in query('data_works', 'redbook_comments_for_ala', condition):
    #     row = dict()
    #     row['评论ID'] = item['_id']
    #     row['手机号'] = item.get('phone', '无')
    #     row['父级评论ID'] = item.get('father_comment_id')
    #     row['博主类型'] = item.get('account_type', '无')
    #     row['评论内容'] = item.get('content')
    #     fc = query_one('data_works', 'redbook_comments_for_ala',{'_id': item.get('father_comment_id')})
    #     if fc:
    #         row['父级评论内容'] = fc.get('content')
    #         if fc.get('phone'):
    #             row['父级评论是否为己方'] = '是'
    #         else:
    #             row['父级评论是否为己方'] = '否'
    #     row['生效'] =  '是' if int(item.get('is_active')) == 1 else '否'
    #     row['帖子的URL'] = item['post_url']
    #     rows.append(row)
    # df = pd.DataFrame(rows)
    # df.to_excel(f'小红书二级评论明细{start_date}-{end_date}.xlsx', index=False)
    
    

    


if __name__ == '__main__':
    save_comments()
